<template>
  <div class="stats-panel">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="概览" name="overview">
        <div class="overview-stats">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card shadow="hover">
                <div class="stat-item">
                  <div class="stat-title">总错题数</div>
                  <div class="stat-value">{{ overviewStats.totalCount }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover">
                <div class="stat-item">
                  <div class="stat-title">已掌握</div>
                  <div class="stat-value">{{ overviewStats.masteredCount }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover">
                <div class="stat-item">
                  <div class="stat-title">本周新增</div>
                  <div class="stat-value">{{ overviewStats.weeklyNewCount }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover">
                <div class="stat-item">
                  <div class="stat-title">本周正确率</div>
                  <div class="stat-value">{{ overviewStats.weeklyAccuracy }}%</div>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <el-card shadow="hover" class="chart-card">
            <div slot="header" class="clearfix">
              <span>错题趋势</span>
            </div>
            <div class="chart-container">
              <line-chart :chart-data="trendData" />
            </div>
          </el-card>
        </div>
      </el-tab-pane>

      <el-tab-pane label="知识点" name="knowledge">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>知识点分布</span>
            <el-select
              v-model="knowledgeChartType"
              size="mini"
              style="width: 120px; float: right;"
              @change="updateKnowledgeChart"
            >
<!--              <el-option label="饼图" value="pie"></el-option>-->
              <el-option label="环形图" value="ring"></el-option>
            </el-select>
          </div>
          <div class="chart-container">
            <pie-chart
              :chart-data="knowledgeData"
              :chart-type="knowledgeChartType"
              style="width: 600px;height: 300px"
            />
          </div>
        </el-card>

        <el-table
          :data="knowledgeStats"
          style="width: 100%; margin-top: 20px;"
          v-loading="knowledgeLoading"
        >
          <el-table-column prop="knowledgeName" label="知识点" sortable>
            <template slot-scope="scope">
              <el-tag>{{ scope.row.knowledgeName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="count" label="错题数" width="120" sortable>
            <template slot-scope="scope">
              <el-tag type="danger">{{ scope.row.count }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="占比" width="200" sortable>
            <template slot-scope="scope">
              <el-progress
                :percentage="scope.row.percentage"
                :color="getPercentageColor(scope.row.percentage)"
                :show-text="false"
              />
              <span style="margin-left: 10px;">{{ scope.row.percentage }}%</span>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="题型" name="type">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>题型分布</span>
          </div>
          <div class="chart-container">
            <bar-chart :chart-data="typeData" style="height: 300px;width: 800px"/>
          </div>
        </el-card>

        <el-table :data="typeStats" style="width: 100%; margin-top: 20px;">
          <el-table-column prop="typeName" label="题型"></el-table-column>
          <el-table-column prop="count" label="错题数" width="100"></el-table-column>
          <el-table-column label="占比" width="150">
            <template slot-scope="scope">
              <el-progress :percentage="scope.row.percentage" :color="getPercentageColor(scope.row.percentage)"></el-progress>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { getOverviewStats, getKnowledgeStats, getTypeStats } from '@/api/wrongQuestion'
import LineChart from '@/views/stat/components/LineChart.vue'
import PieChart from '@/views/stat/components/PieChart'
import BarChart from '@/views/stat/components/BarChart'

export default {
  name: 'StatsPanel',
  components: { LineChart, PieChart, BarChart },
  props: {
    bookId: {
      type: Number,
      default: null
    },
    userId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      knowledgeChartType: 'ring', // 'pie'或'ring'
      knowledgeLoading: false,
      activeTab: 'overview',
      overviewStats: {
        totalCount: 0,
        masteredCount: 0,
        weeklyNewCount: 0,
        weeklyAccuracy: 0
      },
      knowledgeStats: [],
      typeStats: [],
      trendData: {
        dates: [],
        newData: [],
        reviewData: [],
        accuracyData: []
      },
      knowledgeData: {
        labels: [],
        data: []
      },
      typeData: {
        labels: [],
        data: []
      }
    }
  },
  created() {
    this.loadOverviewStats()
    this.loadKnowledgeStats()
    this.loadTypeStats()
  },
  methods: {
    // 更新图表类型
    updateKnowledgeChart() {
      // 这里可以通过强制重新渲染 PieChart 组件来应用新的图表类型
      this.knowledgeData = {...this.knowledgeData}
    },

    // 按知识点练习
    handlePracticeByKnowledge(knowledgeId) {
      this.$router.push({
        path: '/wrongQuestion/practice',
        query: {
          bookId: this.bookId,
          knowledgeId
        }
      })
    },
    // 加载概览统计
    loadOverviewStats() {
      getOverviewStats(this.userId, this.bookId).then(response => {
        this.overviewStats = response.data

        // 修正数据结构以匹配LineChart组件
        this.trendData = {
          columns: ['日期', '新增错题', '复习错题', '正确率'],
          rows: [
            { name: '周一', value: 5, review: 10, accuracy: 60 },
            { name: '周二', value: 3, review: 8, accuracy: 65 },
            { name: '周三', value: 7, review: 15, accuracy: 70 },
            { name: '周四', value: 2, review: 12, accuracy: 75 },
            { name: '周五', value: 4, review: 18, accuracy: 80 },
            { name: '周六', value: 1, review: 5, accuracy: 85 },
            { name: '周日', value: 0, review: 2, accuracy: 90 }
          ]
        }
      })
    },
    // 加载知识点统计
    loadKnowledgeStats() {
      getKnowledgeStats(this.userId, this.bookId).then(response => {
        this.knowledgeStats = response.data

        // 计算总数
        const total = this.knowledgeStats.reduce((sum, item) => sum + item.count, 0)

        // 计算百分比
        this.knowledgeStats.forEach(item => {
          item.percentage = Math.round((item.count / total) * 100)
        })

        // 准备图表数据 - 调整为 PieChart 需要的格式
        this.knowledgeData = {
          columns: ['知识点'], // 系列名称
          rows: this.knowledgeStats.map(item => ({
            name: item.knowledgeName, // 知识点名称
            value: item.count         // 错题数量
          }))
        }
      })
    },
    // 加载题型统计
    loadTypeStats() {
      getTypeStats(this.userId, this.bookId).then(response => {
        this.typeStats = response.data

        // 计算总数
        const total = this.typeStats.reduce((sum, item) => sum + item.count, 0)

        // 计算百分比
        this.typeStats.forEach(item => {
          item.percentage = Math.round((item.count / total) * 100)
        })

        // 修正为 BarChart 需要的格式
        this.typeData = {
          columns: ['错题数'], // 系列名称
          rows: this.typeStats.map(item => ({
            name: item.typeName, // 题型名称
            value: item.count    // 错题数量
          }))
        }
      })
    },
    // 获取进度条颜色
    getPercentageColor(percentage) {
      if (percentage > 80) {
        return '#f56c6c'
      } else if (percentage > 60) {
        return '#e6a23c'
      } else if (percentage > 40) {
        return '#5cb87a'
      } else if (percentage > 20) {
        return '#1989fa'
      } else {
        return '#6f7ad3'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.stats-panel {
  padding: 20px;

  .overview-stats {
    .stat-item {
      text-align: center;

      .stat-title {
        font-size: 14px;
        color: #666;
        margin-bottom: 10px;
      }

      .stat-value {
        font-size: 24px;
        font-weight: bold;
        color: #333;
      }
    }

    .chart-card {
      margin-top: 20px;
    }
  }

  .chart-container {
    height: 300px;
  }
}
/* 在 StatsPanel 的样式中添加 */
.knowledge-stats {
  .chart-container {
    height: 400px;
    position: relative;
  }

  .el-table {
    .el-tag {
      margin-right: 5px;
    }

    .el-progress {
      display: inline-block;
      width: calc(100% - 50px);
      vertical-align: middle;
    }
  }
}


</style>
